package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a08_组合总和2复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/1/2
 */
public class a08_组合总和2复习1 {
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        traversal(result, path, nums, target, 0, used,0);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           int targetSum,
                           int sum,
                           boolean[] used,
                           int startIdx){
        if (sum > targetSum) {
            return;
        }
        if (sum == targetSum) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIdx; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i-1] && !used[i-1]){
                continue;
            }
            path.add(nums[i]);
            sum = sum + nums[i];
            used[i] = true;
            traversal(result, path, nums, targetSum, sum, used,i + 1);
            path.removeLast();
            sum = sum - nums[i];
            used[i] = false;
        }
    }
}
